package com.glor.operation.common.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * Created by heylear.cai on 2016/2/18.
 */
@Slf4j
public class FreemarkerFilter implements Filter {

    private Locale locale;

    private ApplicationContext ctx;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String localeStr = filterConfig.getInitParameter("locale");
        if(StringUtils.isNotBlank(localeStr)){
            locale = new Locale(localeStr);
        }else {
            locale = Locale.getDefault();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        if(ctx == null){
            ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
            if(null == ctx){
                throw new ExceptionInInitializerError("spring context is not loaded!");
            }
        }

        String name = request.getRequestURI();
        name = name.substring(1, name.lastIndexOf(".ftl"));
        FreeMarkerViewResolver viewResolver = ctx.getBean(FreeMarkerViewResolver.class);

        try {
            View view = viewResolver.resolveViewName(name, locale);
            view.render(null, request, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServletException(e);
        }
    }

    @Override
    public void destroy() {

    }
}
